<?php

if (function_exists('getMicrotime')) {
    function getMicrotime(): float
    {
        return round(microtime(true)*1000);
    }
}

if (!function_exists('handlerUrl')) {
    /**
     * @param string $url
     * @param array $params
     * @return string
     */
    function handlerUrl(string $url, array $params): string
    {
        if (!$params) {
            return $url;
        }
        $query = http_build_query($params);
        if (strpos($url, '?')) {
            return rtrim($url, '&').'&'.$query;
        }
        return $url.'?'.$query;
    }
}

if (!function_exists('filterStr')) {
    /**
     * @param string $value
     * @param string $char
     * @return string
     */
    function filterStr(string $value, string $char = '\\'): string
    {
        if (empty($value)) {
            return '';
        }
        return str_replace(
            [$char, '%', '_'],
            [$char.$char, $char.'%', $char.'_'],
            trim($value)
        );
    }
}

if (!function_exists('codeToString')) {
    /**
     * @param string $str
     * @return string
     */
    function codeToString(string $str): string
    {
        return str_replace([" ", "　", "\t", "\n", "\r"], ['&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;', "\n", "\r"], $str);
    }
}

if (!function_exists('htmlText')) {
    /**
     * @param string $str
     * @param int $leg
     * @return string
     */
    function htmlText(string $str, int $leg = 150): string
    {
        $intro = preg_replace("/\s*<.*?>\s*/", "", $str);
        return mb_substr(str_replace(["&nbsp;", " ", "??"], [" ", "", " "], $intro), 0, $leg) . "...";
    }
}

if (!function_exists('byteCount')) {
    /**
     * 格式化字节
     * @param int $bit
     * @param string $delimiter
     * @return string
     */
    function byteCount(int $bit, string $delimiter = ''): string
    {
        $type = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        for ($i = 0; $bit >= 1024 && $i < 5; $i++) {
            $bit /= 1024;
        }
        return round($bit, 2) . $delimiter . $type[$i];
    }
}

if (!function_exists('createRandom')) {
    /**
     * 产生随机字符串
     * @param int $length
     * @param string $chars
     * @return string
     */
    function createRandom(int $length, string $chars = '0123456789'): string
    {
        $hash = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
}

if (!function_exists('xmlToArray')) {
    /**
     * 将XML转为array
     * @param $xml
     * @return array
     */
    function xmlToArray($xml): array
    {
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }
}

if (!function_exists('sexists')) {
    /**
     * 查找字符串开头
     * @param $string
     * @param $find
     * @return bool
     */
    function sexists($string, $find): bool
    {
        return strpos($string, $find) !== false;
    }
}

if (!function_exists('priceFormat')) {
    /**
     * 价格格式化
     * @param $price
     * @return string
     */
    function priceFormat($price): string
    {
        if (empty($price)) {
            return '';
        }
        $prices = explode('.', $price);
        if ((int)$prices[1] <= 0) {
            return $prices[0];
        }
        if (isset($prices[1][1]) && $prices[1][1] <= 0) {
            $price = $prices[0] . '.' . $prices[1][0];
        }
        return $price;
    }
}

if (!function_exists('setMedias')) {
    /**
     * 补充图片连接 升级版
     * @param array $list
     * @param $fields
     * @return array
     */
    function setMedias(array $list, $fields): array
    {
        if (empty($list)) {
            return [];
        }
        if ($fields && is_string($fields)) {
            $fields = explode(',', $fields);
        }
        foreach ($list as $key => $value) {
            if (is_array($value) && is_array($fields)) {
                foreach ($fields as $field) {
                    if (isset($value[$field])) {
                        $list[$key][$field] = toMedia($value[$field]);
                    }
                }
                continue;
            }
            $list[$key] = toMedia($value);
        }
        return $list;
    }
}

if (!function_exists('toMedia')) {
    /**
     * @param string $src
     * @param string $storage
     * @param bool $isCache
     * @return string
     */
    function toMedia(string $src, string $storage = 'local', bool $isCache = false): string
    {
        if (empty($src) || (strpos($src, '//') === 0) || (strpos($src, 'http://') === 0) || (strpos($src, 'https://') === 0)) {
            return $src;
        }
        switch ($storage) {
            case 'oss':
            case 'cos':
            case 'kodo':
                $src = config('custom.upload'.$storage.'.url').'/'.$src;
                break;
            default:
                $src = config('app.url').'/storage/'.$src;
                break;
        }
        $isCache && $src .= "?v=" . time();
        return $src;
    }
}

if (!function_exists('formatDate')) {
    /**
     * 格式化时间
     * @param $date
     * @return string
     */
    function formatDate($date): string
    {
        $time = is_numeric($date) ? $date : strtotime($date);
        $difference = time() - $time;
        switch ($difference) {
            case $difference <= 60 :
                $msg = '刚刚';
                break;
            case $difference > 60 && $difference <= 3600 :
                $msg = floor($difference / 60) . '分钟前';
                break;
            case $difference > 3600 && $difference <= 86400 :
                $msg = floor($difference / 3600) . '小时前';
                break;
            case $difference > 86400 && $difference <= 2592000 :
                $msg = floor($difference / 86400) . '天前';
                break;
            case $difference > 2592000 &&  $difference <= 7776000:
                $msg = floor($difference / 2592000) . '个月前';
                break;
            case $difference > 7776000:
                $msg = '很久以前';
                break;
            default:
                $msg = date('Y-m-d H:i:s', $time);
                break;
        }
        return $msg;
    }
}

if (!function_exists('listToTree')) {
    /**
     * @param array $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    function listToTree(array $list, string $pk = 'id', string $pid = 'parent_id', string $child = '_child', int $root = 0): array
    {
        if (empty($list)) {
            return [];
        }
        $arr = [];
        foreach ($list as $sorData) {
            if ((int)$sorData[$pid] === $root) {
                $sorData[$child] = listToTree($list, $pk, $pid, $child, $sorData[$pk]);
                $arr[] = $sorData;
            }
        }
        return $arr;
    }
}

if (!function_exists('treeToList')) {
    /**
     * 将树还原成列表
     * @param array $tree
     * @param string $child
     * @param string $order
     * @param array $list
     * @return array
     */
    function treeToList(array $tree, string $child = '_child', string $order = 'id', array &$list = []): array
    {
        if (empty($tree)) {
            return [];
        }
        foreach ($tree as $value) {
            $refer = $value;
            if (isset($refer[$child])) {
                unset($refer[$child]);
                treeToList($value[$child], $child, $order, $list);
            }
            $list[] = $refer;
        }
        return listSortBy($list, $order);
    }
}

if (!function_exists('listSortBy')) {
    /**
     * 对集合进行排序
     * @param array $list
     * @param string $field
     * @param string $sort
     * @return array
     */
    function listSortBy(array $list, string $field, string $sort = 'asc'): array
    {
        if (empty($list)) {
            return [];
        }
        $refer = $resultSet = [];
        foreach ($list as $i => $data) {
            $refer[$i] = &$data[$field];
        }
        if ($sort === 'asc') {
            asort($refer);// 正向排序
        } elseif ($sort === 'desc') {
            arsort($refer);// 逆向排序
        } elseif ($sort === 'nat') {
            natcasesort($refer);
        }
        foreach ($refer as $key => $val) {
            $resultSet[] = &$list[$key];
        }
        return $resultSet;
    }
}

if (!function_exists('getClientIp')) {
    function getClientIp(): string
    {
        $ipStr = '0.0.0.0';
        if (getenv('HTTP_CLIENT_IP')) {
            $ipStr = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_REAL_IP')) {
            $ipStr = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
            $ips = explode(',', $ip);
            $ipStr = $ips[0];
        } elseif (getenv('REMOTE_ADDR')) {
            $ipStr = getenv('REMOTE_ADDR');
        }
        return $ipStr;
    }
}
